<template>
  <div class="userBox">
    <div class="userContent">
      <!--上半部分-->
      <div class="userTop">
        <!--头像-->
        <el-upload
            class="avatar-uploader upload"
            :show-file-list="false"
            :before-upload="uploadImage"
            drag
        >
          <img :src="newUserInfo.header" class="avatar header" alt="图片走丢了"/>
        </el-upload>
        <!--个人信息-->
        <div class="contentBox">
          <el-button @click="isShowUpdatePassword = true">修改密码</el-button>
          <div class="userName">
            <el-tooltip
                class="box-item"
                effect="dark"
                content="点击修改用户名"
                placement="top-start"
                :visible="visible"
            >
              <span v-show="!isEdit" @click="updateName">{{newUserInfo.name}}</span>
            </el-tooltip>
            <el-input
              v-show="isEdit"
              ref="name"
              v-model="newUserInfo.name"
              @blur="isEdit = false"
            />
          </div>
        </div>
        <!--操作按钮-->
        <div class="btnBox">
          <el-button type="primary" @click="submit">保存修改</el-button>
          <el-button @click="router.back()">返回</el-button>
          <el-button type="danger" @click="logout">退出</el-button>
        </div>
      </div>
      <!--下半部分-->
      <div class="userBottom">
        <!--配色-->
        <div class="userColor">
          <h3>个性设置</h3>
          <div class="demo-color-block">
            <span class="demonstration">字体颜色</span>
            <el-color-picker v-model="newUserInfo.color" show-alpha/>
          </div>
          <div class="demo-color-block">
            <span class="demonstration">背景颜色</span>
            <el-color-picker v-model="newUserInfo.bg" show-alpha/>
          </div>
          <div class="demo-color-block">
            <span class="demonstration">激活状态颜色</span>
            <el-color-picker v-model="newUserInfo.primary" show-alpha/>
          </div>
        </div>
        <!--小部件-->
        <el-button type="primary" @click="isShowDrawer = true">更改小部件</el-button>
      </div>
    </div>
    <!--侧边弹窗，选择小部件-->
    <el-drawer v-model="isShowDrawer" :with-header="false">
      <div
          class="widgetItem"
          :class="{active : item.wid === newUserInfo.wid}"
          v-for="item in widgetList"
          :key="item.wid"
          @click="toggleWidget(item.wid)"
      >
        <img :src="item.image" alt="">
      </div>
    </el-drawer>
    <!--更改密码-->
    <el-drawer direction="ttb" class="drawerPassword" v-model="isShowUpdatePassword" :with-header="false">
      <el-space fill style="max-width: 500px;">
        <el-input
          clearable
          type="password"
          v-model.trim="password.oldPassword"
          placeholder="当前密码"
          show-password
        />
        <el-input
          v-model.trim="password.newPassword"
          placeholder="新密码"
          clearable
          type="password"
          show-password
        />
        <el-input
          v-model.trim="password.verifyPassword"
          placeholder="确认密码"
          clearable
          type="password"
          show-password
        />
        <div class="passwordBtn">
          <el-button @click="isShowUpdatePassword = false">取消</el-button>
          <el-button type="primary" @click="updatePassword">提交</el-button>
        </div>
      </el-space>
    </el-drawer>
  </div>
</template>

<script setup>
  import {nextTick,onBeforeMount,reactive,ref} from "vue"
  import {useRouter} from "vue-router"
  import {ElMessage} from "element-plus"

  import {useUserStore} from "../config/pinia/user.js"
  import {useWidgetStore} from "../config/pinia/widget.js"
  import {http} from "../config/axios/index.js"

  //用户状态
  const userStore = useUserStore()

  //小部件
  const widgetStore = useWidgetStore()

  //更新后的状态
  const newUserInfo = reactive(userStore.userInfo)

  //路由器对象
  const router = useRouter()

  //上传头像
  async function uploadImage(file){
    const formData = new FormData()
    formData.append("file",file)
    const res = await http({
      method: "POST",
      data: formData,
      url: "utils/upload_pic?type=user"
    })
    if(res.data.code === 0){
      newUserInfo.header = res.data.data.url
    }
    return false
  }

  //是否编辑用户名
  let isEdit = ref(false)

  //显示提示
  let visible = ref(true)

  //获取用户名的输入框
  const name = ref(null)

  //开启编辑用户名
  function updateName(){
    isEdit.value = true
    visible.value = false
    nextTick(()=>{
      name.value.focus()
    })
  }

  //退出
  function logout(){
    userStore.logout()
    router.replace({
      name: "Sign"
    })
  }

  //是否显示侧边弹窗
  let isShowDrawer = ref(false)

  //小部件列表
  const widgetList = reactive([])

  //获取小部件
  async function getWidget(){
    const res = await http({
      method: "GET",
      url: "widget/get_widget"
    })
    if(res.data.code === 0){
      widgetList.push(...res.data.data.widgetList)
    }
  }

  //切换小部件
  function toggleWidget(id){
    newUserInfo.wid = id
    isShowDrawer.value = false
  }

  //提交数据
  async function submit(){
    const res = await http({
      method: "POST",
      url: "user/update_user",
      data: newUserInfo
    })
    if(res.data.code === 0){
      //变更用户状态
      sessionStorage.setItem("masterwork",JSON.stringify(newUserInfo))
      await userStore.init()
      //切换小部件
      await widgetStore.toggleWidget(newUserInfo.wid)
      router.back()
    }
  }

  //密码信息
  const password = reactive({
    oldPassword: "",
    newPassword: "",
    verifyPassword: ""
  })

  //是否显示修改密码
  let isShowUpdatePassword = ref(false)

  //修改密码
  async function updatePassword(){
    const {oldPassword,newPassword,verifyPassword} = password
    //验证密码
    if(oldPassword === "" || newPassword === "" || verifyPassword === ""){
      return ElMessage({
        showClose: true,
        message: "请填写所有输入框哦",
        center: true,
      })
    }else if(oldPassword === newPassword){
      return ElMessage({
        showClose: true,
        message: "新密码与旧密码一致",
        center: true,
      })
    }else if(newPassword !== verifyPassword){
      return ElMessage({
        showClose: true,
        message: "确认密码错误",
        center: true,
      })
    }
    //发起请求，修改密码
    const res = await http({
      method: "POST",
      url: "user/update_password",
      data: {
        uid: userStore.userInfo.uid,
        account: userStore.userInfo.account,
        password: oldPassword,
        newPassword: newPassword
      }
    })
    if(res.data.code === 0){
      isShowUpdatePassword.value = false
      for (let key in password) {
        password[key] = ""
      }
    }
    ElMessage({
      showClose: true,
      message: res.data.msg,
      center: true,
    })
  }

  //组件挂载前
  onBeforeMount(()=>{
    if(!userStore.isLogin){
      return router.push({name: "Sign"})
    }
    getWidget()
  })
</script>

<style scoped>
  .userBox{
    width: 100%;
    height: 100vh;
    overflow: auto;
    padding: 20px;
    background-image: url("../assets/user_bg.jpg");
    background-repeat: no-repeat;
    background-size: cover;
    background-attachment: fixed;
    background-position-y: bottom;
    color: var(--el-text-color-primary);
  }
  .userContent{
    width: 100%;
    max-width: 700px;
    margin: 0 auto;
    padding: 20px;
    border-radius: 5px;
    box-shadow: 0 0 10px 0 rgba(0,0,0,.5);
    backdrop-filter: blur(5px);
  }
  /*上半部分*/
  .userTop{
    display: flex;
  }
  /*头像*/
  .upload{
    width: 150px;
    height: 150px;
    margin: 0 auto;
    flex-shrink: 0;
  }
  :deep(.el-upload-dragger){
    padding: 0;
  }
  .header{
    width: 150px;
    height: 150px;
    display: block;
  }
  /*个人信息*/
  .contentBox{
    flex: 1;
    padding: 0 20px;
    display: flex;
    flex-direction: column;
    align-items: start;
    justify-content: space-between;
  }
  .contentBox .userName span{
    font-size: 20px;
    font-weight: 600;
    cursor: pointer;
  }
  /*操作按钮*/
  .btnBox{
    width: 250px;
    text-align: center;
    flex-shrink: 0;
  }
  @media (max-width: 800px){
    .userTop{
      flex-direction: column;
      align-items: center;
      height: 340px;
    }
    .contentBox{
      align-items: center;
      padding: 20px;
    }
  }
  /*下半部分*/
  .userBottom{
    padding-top: 20px;
  }
  /*配色*/
  .userColor h3{
    border-left: 5px solid #09c;
    padding-left: 20px;
  }
  .userColor .demo-color-block{
    padding: 10px 0;
  }
  /*选择小部件*/
  .widgetItem{
    padding: 10px;
  }
  .active{
    border: 2px solid #09c;
  }
  .widgetItem img{
    width: 100%;
  }
  /*修改密码*/
  :deep(.drawerPassword .el-drawer__body){
    text-align: center;
  }
  .passwordBtn{
    text-align: left;
  }
</style>